import { Component, OnInit, ViewChild } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { ApiService } from '@core/api.service';
import { DomSanitizer } from '@angular/platform-browser';
import { DatePipe } from '@angular/common';
import { ElectricalnmlComponent } from './components/electricalnml.component';
import { ControlApiService } from '@core/controlApi.service';
import { StationDevtypeService } from '@core/stationDevtype.service';
import { _HttpClient } from '@delon/theme';
import { TreeTools } from '@core/treeTools.tool';
import { environment } from '../../../../environments/environment';

@Component({
    selector: 'app-controlcommand',
    templateUrl: './command.component.html',
    styleUrls: ['./command.component.less']
})

export class ControlCommandComponent implements OnInit {
    @ViewChild('electricalnml', { static: false }) electricalnml: ElectricalnmlComponent;
    processAct = false;
    stationSelect: any = [];
    devNameIf = true;
    devNameSelect: any = [];
    sjValue: any = '';
    scValue: any = '5';
    selectedIndex = 0;
    selectedChildIndex = 0;
    formatData: any = [];
    czjyAlarmType = '';
    nav = [
        { 'id': '1', 'icon': 'area-chart', 'name': '智能分析' },
        { 'id': '2', 'icon': 'file-pdf', 'name': '图纸信息' },
        { 'id': '3', 'icon': 'gold', 'name': '应急备品' },
        { 'id': '4', 'icon': 'idcard', 'name': '应急出动' },
        { 'id': '5', 'icon': 'qrcode', 'name': '设备信息' },
        { 'id': '6', 'icon': 'project', 'name': '检修信息' },
        { 'id': '7', 'icon': 'file-exclamation', 'name': '问题记录' },
        { 'id': '8', 'icon': 'export', 'name': '历史故障' },
        { 'id': '9', 'icon': 'alert', 'name': '报警案例' },
        { 'id': '10', 'icon': 'pic-left', 'name': '登销记模板' },
        { 'id': '11', 'icon': 'message', 'name': '处置建议' }
    ];
    gzxxData: any = [];
    bjalData: any = [];
    jxjlData: any = [];
    wtjlData: any = [];
    bumenValue1 = '';
    xingmingValue1 = '';
    xingmingValue2 = '';
    bumenValue2 = '';
    bumenSelect2: any = [];
    xingmingValue3 = '';
    yingjiList1: any = [];
    yingjiList2: any = [];
    yingjiList3: any = [];
    bpbjList: any = [];
    tuzhi: any = [];
    tupian: any = [];
    zctIframe: any;
    zctIframeFull: any;
    zctIframeUrl = '';
    gzxxframe: any;
    gzxxframeFull: any;
    queryParams: any;
    alarmtyUrl = '';
    alarmTypeIf = true;
    alarmTypeSelect: any = [];
    alarmTypeList: any = [];
    alarmTypeId = '';
    alarmTypeName = '';
    devTypeIf = true;
    devTypeSelect: any = [];
    devTypeList: any = [];
    devTypeId = '';
    devTypeName = '';
    stepNameValue = '';
    stepNameSelect: any = [];
    processParam: any = {};
    intelligent = true;
    noDataframe = false;
    fullVisible = false;
    fullTitle = '';
    fullType = '';
    themeClass = 'whitetheme';
    selectClass = 'defaultSelect';
    popClass = '';
    tabBarStyle = { 'margin': '0 20px', 'color': '#000' };
    bpbjList_filter: any;
    sblxFilterText: any;
    bpmcFilterText: any;
    stationId = '';
    stationName = '';
    stationlist: any = [];
    devNameId = '';
    devNameText = '';
    treeNodeStyle = { 'max-width': '300px', 'max-height': '400px', 'overflow-y': 'auto', 'overflow-x': 'hidden' };
    bumenSelect3: any = [];
    yingjiPage: any = 1;
    yingjiLimit: any = 10;
    bumenValue3: any = '';
    yingjiTotal: number;
    yjQrcodeSrc = '';
    dxjTemplateData: any = {};
    dxjFontSize = 16;
    controlczjyStatus = true;
    electricalnmlStatus = true;

    constructor(
        private apiService: ApiService,
        private activatedRoute: ActivatedRoute,
        private sanitizer: DomSanitizer,
        private datePipe: DatePipe,
        public treeTools: TreeTools,
        private http: _HttpClient,
        private controlApiService: ControlApiService,
        private statdevtype: StationDevtypeService
    ) { }

    ngOnInit() {
        this.activatedRoute.queryParams.subscribe(res => {
            this.queryParams = {
                'NID': res.NID,
                'ALARMTEXT': decodeURI(decodeURI(res.ALARMTEXT)),
                'ALARMTYPE': res.ALARMTYPE,
                'DEVNAME': decodeURI(decodeURI(res.DEVNAME).replace(/%23/g, '#')),
                'DEVNAMEID': res.DEVNAMEID,
                'DEVTYPE': res.DEVTYPE,
                'DEVTYPEID': res.DEVTYPEID,
                'STATIONID': res.STATIONID,
                'STATIONNAME': decodeURI(decodeURI(res.STATIONNAME)),
                'TIME': res.TIME,
                'SCVALUE': res.SCVALUE,
                'ALARMDESCRIPTION': res.ALARMDESCRIPTION
            };
            if (this.queryParams.SCVALUE) {
                this.scValue = this.queryParams.SCVALUE;
            }
            this.sjValue = this.queryParams.TIME;
            this.stationId = this.queryParams.STATIONID;
            this.alarmTypeId = this.queryParams.ALARMTYPE;
            this.devNameText = this.queryParams.DEVNAME;
            this.devNameId = this.queryParams.DEVNAMEID;
            this.devTypeId = this.queryParams.DEVTYPEID;
            // 车站名称
            this.getorgstatree();
            // 处置流程
            this.menuProcess();
            this.loadData();
        });
    }

    processClick(title) {
        if (title && title.includes('应急出动')) {
            this.selectedIndex = 3;
        }
    }

    loadData() {
        this.queryParams.STATIONID = this.stationId;
        this.queryParams.DEVTYPEID = this.devTypeId;
        this.queryParams.ALARMTYPE = this.alarmTypeId;
        this.queryParams.DEVNAME = this.devNameText;
        this.queryParams.DEVNAMEID = this.devNameId;
        this.intelligent = false;
        this.electricalnmlStatus = false;
        this.noDataframe = true;
        // 获取故障图纸
        this.getAlarmType();

        setTimeout(() => {
            // 站场回放
            const beginDate = this.datePipe.transform(new Date(this.sjValue).getTime() - 1 * 15 * 60 * 1000, 'yyyy-MM-dd HH:mm:ss');
            const endDate = this.datePipe.transform(new Date(this.sjValue).getTime() + 1 * 10 * 60 * 1000, 'yyyy-MM-dd HH:mm:ss');
            this.zctIframe = this.sanitizer.bypassSecurityTrustHtml(
                '<iframe src="/csmis/staht/HTtest.jsp?setZoom=1&staId=' +
                this.stationId + '&beginDate=' + beginDate + '&endDate=' +
                endDate + '" frameborder="0" style="width:100%;height:430px"></iframe>');
            this.zctIframeUrl = this.stationId;
            this.intelligent = true;
            this.electricalnmlStatus = true;
            this.noDataframe = false;
        }, 500);
    }
    formatTreeSelect(resdata) {
        const select: any = [];
        for (const item of resdata) {
            select.push({
                id: item.ID,
                name: item.VC_NAME
            });
        }
        return select;
    }
    // 处置流程
    menuProcess() {
        this.controlApiService.menuProcess().subscribe((res: any) => {
            this.stepNameSelect = [];
            for (const item of res) {
                this.stepNameSelect.push({ 'value': item.cid + '', 'name': item.content });
            }
            this.stepNameValue = this.queryParams.ALARMDESCRIPTION;
            this.processParam.ALARMDESCRIPTION = this.stepNameValue;
            this.processAct = true;
        });
    }
    // 同类报警案例
    listByBjlx() {
        this.controlApiService.listByBjlx(this.alarmTypeId).subscribe((res: any) => {
            if (res.type === 'success') {
                const data = res.response.data;
                data.forEach((item, index) => {
                    if (data.hasOwnProperty(index)) {
                        this.bjalData.push({
                            time: this.datePipe.transform(item.U_TIME * 1000, 'yyyy-MM-dd'),
                            address: item.STATIONNAME,
                            name: item.DEVNAME,
                            dev: item.DEV_TYPE,
                            type: item.ALARMTYPE,
                            text: item.ALARMTEXT,
                            adv: item.CZJY
                        });
                    }
                });
            }
        });
    }
    // 获取故障图纸
    getAlarmType() {
        this.alarmtypeid(this.queryParams.ALARMTYPE).subscribe((res: any) => {
            if (res.msg === 'Ok') {
                if (res.data.length) {
                    this.noDataframe = false;
                    this.alarmtyUrl = '<iframe src="/csmis/staht/guidaodianluguzhang.html?alarmelemapid=' +
                        res.data[0].alarmelemapid + '&alarmelemapnodes=' + res.data[0].alarmelemapnodes +
                        '" frameborder="0" style="width:100%;height:430px"></iframe>';
                    this.gzxxframe = this.sanitizer.bypassSecurityTrustHtml(this.alarmtyUrl);
                } else {
                    this.noDataframe = true;
                }
            }
        });
    }
    getQrcode() {
        if (!this.stationId || !this.devNameText) {
            return;
        }
        const param = {
            staId: this.stationId || '',
            devName: this.devNameText || ''
        };
        this.getQrcodeUrl(param).subscribe(res => {
            if (res.msg === 'Ok') {
                const _url = res.meta.imageUrl;
                this.yjQrcodeSrc = environment.apiBase + '/csmis/' + _url;
            }
        });
    }
    // 获取应急人员二维码 param staId=&devName=1&devType=S0104
    getQrcodeUrl(param) {
        const url = environment.project + '/workdoor/getTrafficImage';
        return this.http.get(url, param);
    }
    themeChenge(e) {
        this.processAct = false;
        this.themeClass = e;
        switch (e) {
            case 'blacktheme':
                this.selectClass = 'controlSelect';
                this.popClass = 'processWrap';
                this.tabBarStyle = { 'margin': '0 20px', 'color': '#fff' };
                break;
            case 'whitetheme':
                this.selectClass = 'defaultSelect';
                this.popClass = '';
                this.tabBarStyle = { 'margin': '0 20px', 'color': '#000' };
                break;
        }
        setTimeout(() => {
            this.processAct = true;
        }, 500);
    }
    /**
     * 将大数组分成长度为num 的若干小数组
     * @param arr 任意数值
     * @param num 分开的小数组长度
     */
    splitArray(arr: any[], num: number) {
        if (!arr.length) {
            return arr;
        }
        const newArr = [];
        let tempArr = [];
        for (let i = 0; i < arr.length; i++) {
            const el = arr[i];
            if ((i + 1) % ((newArr.length + 1) * num + 1) > 0) {// 同一排元素
                tempArr.push(el);
            } else {// 下一排元素
                newArr.push([...tempArr]);
                tempArr = [el];
            }
        }
        return newArr;
    }
    // 设备履历信息
    devInfo(id, name) {
        if (!id || !name) {
            return;
        }
        this.formatData = [];
        this.devRecordInfo(id, name).subscribe((res: any) => {
            if (!res || !res.length) {
                return;
            }
            const newRes = [];
            res[0].forEach(el => {
                newRes.push(el.name);
                newRes.push(el.value);
            });
            this.formatData = this.splitArray(newRes, 6);
        });
    }
    // 设备履历信息
    devRecordInfo(id, name) {
        id = !id ? '' : id;
        name = !name ? '' : name;
        const url = environment.apiBase + '/csmis/stations/devinfo.jwt?stationid=' + id + '&name=' + name;
        return this.http.get(url);
    }
    // 设备历史信息故障
    listByCz(id, name) {
        if (!id || !name) {
            return;
        }
        this.gzxxData = [];
        this.controlApiService.listByCz(id, name).subscribe((res: any) => {
            if (res.type === 'success') {
                const data = res.response.data;
                for (const item of data) {
                    this.gzxxData.push({
                        time: this.datePipe.transform(item.U_TIME * 1000, 'yyyy-MM-dd'),
                        address: item.STATIONNAME,
                        name: item.DEVNAME,
                        info: item.ALARMTEXT,
                        adv: item.CZJY
                    });
                }
            }
        });
    }
    // 检修信息
    getWorkByDevName(id, name) {
        if (!id || !name) {
            return;
        }
        this.jxjlData = [];
        this.controlApiService.getWorkByDevName(id, name).subscribe((res: any) => {
            for (const item of res) {
                this.jxjlData.push({
                    'time': this.datePipe.transform(item.DT_WORK$DAY, 'yyyy-MM-dd'),
                    'id': item.N_ID,
                    'type': item.VC_PROJECT,
                    'human': item.VC_WA$PERSON
                });
            }
        });
    }
    // 问题记录
    getProbByDevname(devName, id) {
        if (!id || !devName) {
            return;
        }
        this.wtjlData = [];
        this.controlApiService.getProbByDevname(devName, id).subscribe((res: any) => {
            for (const item of res) {
                this.wtjlData.push({
                    'time': this.datePipe.transform(item.DT_SYS$DATE, 'yyyy-MM-dd'),
                    'id': item.N_ID,
                    'human': item.VC_USER,
                    'level': item.VC_LEVEL,
                    'desc': item.VC_PROBLEM
                });
            }
        });
    }
    // 备品备件
    getspare(id) {
        if (!id) {
            return;
        }
        this.bpbjList = [];
        this.getspareQuery(id).subscribe((res: any) => {
            if (res.msg === 'Ok' && res.data.length) {
                for (const item of res.data) {
                    this.bpbjList.push({
                        'code': item.code,
                        'name': item.name,
                        'station': item.station,
                        'place': item.place,
                        'num': item.num
                    });
                }
            }
        });
        this.bpbjList_filter = this.bpbjList;
    }

    // 备品备件
    getspareQuery(id) {
        const url = environment.project + '/sparepartsStatistics/query?station=' + id;
        return this.http.get(url);
    }
    getspareList() {
        this.bpbjList = [];
        const param = {
            code: this.sblxFilterText || '',
            name: this.bpmcFilterText || '',
        };
        this.apiService.getspareList(param).subscribe((res: any) => {
            if (res.msg === 'Ok' && res.data.length) {
                for (const item of res.data) {
                    this.bpbjList.push({
                        'code': item.code,
                        'name': item.name,
                        'station': item.station,
                        'place': item.place,
                        'num': item.num
                    });
                }
            }
        });
        this.bpbjList_filter = this.bpbjList;
    }
    // 段值班全部人员（部门）
    getAllDuty() {
        const url = environment.apiBase + '/csmis/getAllDep.jwt?yesorno=1';
        return this.http.get(url);
    }
    getZbryBm() {
        if (this.bumenSelect2.length) {
            return;
        }
        this.apiService.departmentsPublicTree().subscribe(res => {
            if (res.length) {
                this.bumenSelect2 = res;
                Object.assign(this.bumenSelect3, res);
            }
        });
    }

    getTrendsperson1() {
        this.yingjiList1 = [];
        this.getzbpersonDuan().subscribe((res: any) => {
            if (res.response && res.response.data && res.response.data.length) {
                this.yingjiList1 = res.response.data;
            }
        });
    }
    getTrendsperson2(id, orgId?) {
        if (!id) {
            return;
        }
        const data = { 'devname': this.xingmingValue2, 'orgId': orgId || '' };
        this.yingjiList2 = [];
        this.getzbperson(id, data).subscribe((res: any) => {
            if (res.pageList.length) {
                this.yingjiList2 = res.pageList;
            }
        });
    }
    // 值班人员
    getzbperson(id, data) {
        let url = environment.apiBase + '/csmis/publicpro/getzbperson.jwt?debug=0';
        if (!!id) {
            url += '&staid=' + id;
        }
        if (!!data.cjorg) {
            url += '&cjorg=' + data.cjorg;
        }
        if (!!data.devname) {
            url += '&devname=' + data.devname;
        }
        if (data.orgId) {
            url += '&orgId=' + data.orgId;
        }
        return this.http.get(url);
    }
    // 值班人员（段）
    getzbpersonDuan() {
        const url = environment.apiBase + '/csmis/duty/getDutyPersonInfo.jwt';
        return this.http.get(url);
    }

    searchPerson1() {
        this.getTrendsperson1();
    }
    searchPerson2() {
        this.getTrendsperson2(this.stationId, this.bumenValue2);
    }
    searchPerson3(page?, limit?) {
        const param = {
            page: page || this.yingjiPage,
            limit: limit || this.yingjiLimit,
            vcDevid: this.bumenValue3 || '',
            vcPersonname: this.xingmingValue3,
            staId: this.stationId,
        };
        this.getYjPerson(param).subscribe((res: any) => {
            this.yingjiList3 = res.data;
            this.yingjiTotal = res.count;
        });
    }

    // 段值班人员（部门）
    getYjPerson(param) {
        const url = environment.project + '/emPersoninfo/query';
        return this.http.get(url, param);
    }
    // 应急出动
    query_yjcd() {
        this.searchPerson1();
        this.searchPerson2();
        this.searchPerson3();
        this.getQrcode();
    }

    onTabIndexChange_yj(index) {
        switch (index) {
            case 1:
                // 站场图纸id=2
                this.stationsSvg(this.stationId);
                // 设备图纸id=2
                this.getDevimage(this.stationId, this.devNameText);
                break;
            case 2:
                // 备品备件id=3
                this.getspare(this.stationId);
                this.query_yjcd();
                break;
            case 3:
                this.getTrendsperson1();// 人员id=4
                this.getTrendsperson2(this.stationId);// 人员id=4
                this.getZbryBm();// 人员id=4
                this.query_yjcd();// 人员id=4
                break;
            case 4:
                // 设备履历信息id=5
                this.devInfo(this.stationId, this.devNameText);
                break;
            case 5:
                // 检修信息id=6
                this.getWorkByDevName(this.stationId, this.devNameText);
                break;
            case 6:
                // 问题记录id=7
                this.getProbByDevname(this.devNameText, this.stationId);
                break;
            case 7:
                // 设备历史信息故障id=8
                this.listByCz(this.stationId, this.devNameText);
                break;
            case 8:
                // 同类报警案例id=9
                this.listByBjlx();
                break;
            case 9:
                // 登销记模板id=10
                this.getDxjTemplate();
                break;
        }
    }
    // 站场图纸
    stationsSvg(id) {
        if (!id) {
            return;
        }
        this.tuzhi = [];
        this.getStationsSvg(id).subscribe((res: any) => {
            const data = res.response.data;
            if (data) {
                for (const item of data) {
                    const link = window.location.protocol + '//' + window.location.host + '/csmis/dev_image/visio/'
                        + item.LH + '/' + item.ID + '-' + item.NAME.replace(/#/g, '%23');
                    this.tuzhi.push({ 'name': item.NAME, 'url': link + '.png', 'svg': link + '.svg' });
                }
            }
        });
    }
    getStationsSvg(id) {
        const url = environment.apiBase + '/csmis/stations/svg.jwt?stationid=' + id;
        return this.http.get(url);
    }
    // 设备图纸
    getDevimage(id, name) {
        if (!id || !name) {
            return;
        }
        this.tupian = [];
        this.getDevNameImage(id, name).subscribe((res: any) => {
            const data = res.pageList;
            if (data) {
                for (const item of data) {
                    this.tupian.push({
                        'name': item.SVGNAME.replace(/.svg/g, ''),
                        'url': window.location.protocol + '//' + window.location.host +
                            '/csmis/dev_image/' + item.STATION + '/' + item.EQUTYPE + '/' +
                            item.EQUNAME + '/' + item.SVGNAME.replace(/#/g, '%23')
                    });
                }
            }
        });
    }
    // 设备图纸
    getDevNameImage(id, name) {
        const url = environment.apiBase + '/csmis/publicpro/getDevimage.jwt?staid=' + id + '&devname=' + name;
        return this.http.get(url);
    }
    openPic(url: any) {
        window.open(url, '_blank');
    }
    onOk(result: Date): void {
        this.sjValue = this.datePipe.transform(result, 'yyyy-MM-dd');
        const beginDate = this.datePipe.transform(new Date(this.sjValue).getTime() - 1 * 15 * 60 * 1000, 'yyyy-MM-dd');
        const endDate = this.datePipe.transform(new Date(this.sjValue).getTime() + 1 * 10 * 60 * 1000, 'yyyy-MM-dd');
        this.zctIframe = this.sanitizer.bypassSecurityTrustHtml(
            '<iframe src="/csmis/staht/HTtest.jsp?setZoom=1&staId=' + this.stationId + '&beginDate=' +
            beginDate + '&endDate=' + endDate + '" frameborder="0" style="width:100%;height:430px"></iframe>');
        this.zctIframeUrl = this.stationId;
        this.gzxxframe = this.sanitizer.bypassSecurityTrustHtml(this.alarmtyUrl);
    }
    childToList(array, list) {
        list.forEach(item => {
            array.push(item);
            if (item.children && item.children.length) {
                this.childToList(array, item.children);
            }
        })
    }
    // 车站名称
    getorgstatree() {
        this.stationSelect = [];
        this.statdevtype.getStation((resdata) => {
            if (!this.queryParams.STATIONID) {
                switch (resdata[0].children) {
                    case undefined: case 'undefined': case null: case 'null': case false: case 'false':
                        this.stationId = resdata[0].id;
                        this.stationName = resdata[0].text;
                        break;
                    default:
                        this.stationId = resdata[0].children[0].id;
                        this.stationName = resdata[0].children[0].text;
                        break;
                }
            } else {
                this.stationName = this.queryParams.STATIONNAME;
            }
            this.childToList(this.stationlist, resdata);
            this.stationSelect = this.treeTools.formatTreeNode(resdata);
            this.getAllTypesByStaId(this.stationId, 'first');
        });
    }
    // 设备名称
    getstatypedevtree(stationId, devTypeId, type) {
        if (!stationId || !devTypeId) {
            return;
        }
        this.devNameIf = false;
        this.devNameSelect = [];

        this.statdevtype.getDevName(stationId, devTypeId, (resdata) => {
            this.devNameIf = true;
            const data = resdata.response.data;
            if (type === 'first') {
                this.devInfo(this.stationId, this.devNameText);
                this.listByCz(this.stationId, this.devNameText);
                this.getWorkByDevName(this.stationId, this.devNameText);
                this.getDevimage(this.stationId, this.devNameText);
                if (resdata.type === 'success' && data.length) {
                    this.devNameSelect = this.formatTreeSelect(data);
                }
            } else {
                this.devNameId = '';
                this.devNameText = '';
                if (resdata.type === 'success' && data.length) {
                    if (data[0].children) {
                        this.devNameId = data[0].children[0].id;
                        this.devNameText = data[0].children[0].text;
                    } else {
                        this.devNameId = data[0].id;
                        this.devNameText = data[0].text;
                    }
                    this.devInfo(this.stationId, this.devNameText);
                    this.listByCz(this.stationId, this.devNameText);
                    this.getWorkByDevName(this.stationId, this.devNameText);
                    this.getDevimage(this.stationId, this.devNameText);
                    this.devNameSelect = this.formatTreeSelect(data);
                }
            }
        });
    }

    stationChange(value) {
        this.stationId = value;
        setTimeout(() => {
            const beginDate = this.datePipe.transform(new Date(this.sjValue).getTime() - 15 * 60 * 1000, 'yyyy-MM-dd');
            const endDate = this.datePipe.transform(new Date(this.sjValue).getTime() + 1 * 10 * 60 * 1000, 'yyyy-MM-dd');
            this.zctIframe = this.sanitizer.bypassSecurityTrustHtml('<iframe src="/csmis/staht/HTtest.jsp?setZoom=1&staId=' + this.stationId + '&beginDate=' + beginDate + '&endDate=' + endDate + '" frameborder="0" style="width:100%;height:430px"></iframe>');
            this.zctIframeUrl = this.stationId;
            this.gzxxframe = this.sanitizer.bypassSecurityTrustHtml(this.alarmtyUrl);
            // 设备类型(包含设备名称，报警类型)
            this.getAllTypesByStaId(this.stationId, '');
            for (const item of this.stationlist) {
                if (item.id === this.stationId) {
                    this.stationName = item.text;
                    break;
                }
            }
        }, 500);
    }

    // 报警类型
    getjcbjtype(devTypeId, type) {
        if (!devTypeId) {
            return;
        }
        this.alarmTypeIf = false;
        this.alarmTypeSelect = [];

        this.statdevtype.getAlarmType(devTypeId, (resdata) => {
            this.alarmTypeIf = true;
            if (resdata.length) {
                if (type === 'first') {
                    for (const item of resdata) {
                        if (item.children) {
                            for (const list of item.children) {
                                if (this.queryParams.ALARMTYPE === list.id) {
                                    this.alarmTypeId = list.id;
                                    this.alarmTypeName = list.text;
                                    break;
                                }
                            }
                        } else {
                            if (item.children.findIndex(child => child.id === this.queryParams.ALARMTYPE) !== -1) {
                                this.alarmTypeId = this.queryParams.ALARMTYPE;
                                this.alarmTypeName = this.queryParams.ALARMTEXT;
                                break;
                            }
                        }
                    }
                } else {
                    this.alarmTypeId = '';
                    switch (resdata[0].children) {
                        case undefined: case 'undefined': case null: case 'null': case false: case 'false':
                            this.alarmTypeId = resdata[0].id;
                            this.alarmTypeName = resdata[0].text;
                            break;
                        default:
                            this.alarmTypeId = resdata[0].children[0].id;
                            this.alarmTypeName = resdata[0].children[0].text;
                            break;
                    }
                }

                this.alarmTypeSelect = this.treeTools.formatTreeNode(resdata);
                this.childToList(this.alarmTypeList, resdata); 
                this.czjyAlarmType = this.alarmTypeId;
            }
        });
    }

    // 设备类型
    getAllTypesByStaId(stationId, type) {
        if (!stationId) {
            return;
        }
        this.devTypeIf = false;
        this.devTypeSelect = [];

        this.statdevtype.getDevType(stationId, (resdata) => {
            this.devTypeIf = true;
            if (type === 'first') {
                for (const item of resdata) {
                    if (item.children) {
                        for (const list of item.children) {
                            if (this.queryParams.DEVTYPEID === list.id) {
                                this.devTypeId = list.id;
                                this.devTypeName = list.text;
                                break;
                            }
                        }
                    } else {
                        if (this.queryParams.DEVTYPEID === item.id) {
                            this.devTypeId = item.id;
                            this.devTypeName = item.text;
                            break;
                        }
                    }
                }
            } else {
                this.devTypeId = '';
                this.devTypeId = resdata[0].children ? resdata[0].id : resdata[0].children[0].id;
                this.devTypeName = resdata[0].children ? resdata[0].text : resdata[0].children[0].text;
            }
            this.devTypeSelect = this.treeTools.formatTreeNode(resdata);
            this.childToList(this.devTypeList, resdata);
            this.getstatypedevtree(this.stationId, this.devTypeId, type);
            this.getjcbjtype(this.devTypeId, type);
        });
    }

    devTypeChange(value) {
        this.devTypeId = value;
        setTimeout(() => {
            const beginDate = this.datePipe.transform(new Date(this.sjValue).getTime() - 15 * 60 * 1000, 'yyyy-MM-dd');
            const endDate = this.datePipe.transform(new Date(this.sjValue).getTime() + 1 * 10 * 60 * 1000, 'yyyy-MM-dd');
            this.zctIframe = this.sanitizer.bypassSecurityTrustHtml(
                '<iframe src="/csmis/staht/HTtest.jsp?setZoom=1&staId=' + this.stationId +
                '&beginDate=' + beginDate + '&endDate=' + endDate +
                '" frameborder="0" style="width:100%;height:430px"></iframe>');
            this.zctIframeUrl = this.stationId;
            this.gzxxframe = this.sanitizer.bypassSecurityTrustHtml(this.alarmtyUrl);
            this.getstatypedevtree(this.stationId, this.devTypeId, '');
            for (const item of this.devTypeList) {
                if (item.id === this.devTypeId) {
                    this.devTypeName = item.text;
                    break;
                }
            }

            // 人员
            this.getTrendsperson1();
            this.getTrendsperson2(this.stationId);
            this.getProbByDevname(this.devNameText, this.stationId);
            this.getspare(this.stationId);
            this.stationsSvg(this.stationId);
            this.getjcbjtype(value, '');
        }, 500);
    }

    getDevName(id) {
        if (id && this.devNameSelect) {
            let name = '';
            for (const item of this.devNameSelect) {
                if (id === item.id) {
                    name = item.name;
                    break;
                }
            }
            return name;
        }
    }

    devChange(v) {
        this.devNameText = this.getDevName(v);
    }
    // 报警类型
    alarmTypeChange(e) {
        this.alarmTypeId = e;
        this.controlczjyStatus = false;
        setTimeout(() => {
            this.czjyAlarmType = this.alarmTypeId;
            this.controlczjyStatus = true;
            for (const item of this.alarmTypeList) {
                if (item.id === this.stationId) {
                    this.alarmTypeName = item.text;
                    break;
                }
            }
        }, 500);
    }
    fullscreen(name, type) {
        this.fullVisible = true;
        this.fullTitle = name;
        this.fullType = type;

        switch (type) {
            case 'zctIframe':
                const beginDate = this.datePipe.transform(new Date(this.sjValue).getTime() - 15 * 60 * 1000, 'yyyy-MM-dd');
                const endDate = this.datePipe.transform(new Date(this.sjValue).getTime() + 1 * 10 * 60 * 1000, 'yyyy-MM-dd');
                this.zctIframeFull = this.sanitizer.bypassSecurityTrustHtml(
                    '<iframe src="/csmis/staht/HTtest.jsp?setZoom=1.5&staId=' +
                    this.zctIframeUrl + '&beginDate=' + beginDate + '&endDate=' +
                    endDate + '" frameborder="0" style="width:100%;height:800px"></iframe>');
                break;
            case 'intelligent':
                this.intelligent = !this.intelligent;
                break;
            case 'gzxxframe':
                this.gzxxframeFull = this.sanitizer.bypassSecurityTrustHtml(this.alarmtyUrl.replace('height:430px', 'height:800px'));
                break;
        }
    }
    qxtCharts() {
        this.queryParams.STATIONID = this.stationId;
        this.queryParams.DEVTYPEID = this.devTypeId;
        this.queryParams.DEVNAMEID = this.devNameId;
        this.queryParams.ALARMTYPE = this.alarmTypeId;
        this.queryParams.ALARMDESCRIPTION = this.stepNameValue;
        this.intelligent = true;

        this.alarmtypeid(this.alarmTypeId).subscribe((res: any) => {
            if (res.msg === 'Ok') {
                if (res.data.length) {
                    this.alarmtyUrl = '<iframe src="/csmis/staht/guidaodianluguzhang.html?alarmelemapid=' +
                        res.data[0].alarmelemapid + '&alarmelemapnodes=' + res.data[0].alarmelemapnodes + '" frameborder="0" style="width:100%;height:430px"></iframe>';
                    this.gzxxframe = this.sanitizer.bypassSecurityTrustHtml(this.alarmtyUrl);
                }
            }
        });
        this.electricalnml.qxtCharts();
    }

    // 获取故障图纸
    alarmtypeid(id) {
        const url = environment.project + '/emAlarmelect/query?alarmtypeid=' + id;
        return this.http.get(url);
    }
    // 登销记模板
    getDxjTemplate() {
        const param = {
            devName: this.devNameText,
            staId: this.stationId,
        };
        this.getDxjTpl(param).subscribe(res => {
            if (res.type === 'success') {
                const data = res.response.data;
                if (data) {
                    const keys = Object.keys(data);
                    keys.forEach(key => {
                        if (typeof (data[key]) === 'string') {
                            data[key] = data[key].replace(/\n/g, '<br>');
                        }
                    });
                    this.dxjTemplateData = data;
                }
            }
        });
    }

    // 登销记模板
    getDxjTpl(param) {
        const url = environment.apiBase + '/csmis/emt/getByStaIdAndDevName.jwt';
        return this.http.get(url, param);
    }
    font_bigger() {
        this.dxjFontSize++;
    }

    font_smaller() {
        this.dxjFontSize--;
    }

    openModal() {
        this.electricalnml.openModal();
    }
    fullOk() {
        this.fullVisible = false;
        if (this.fullType === 'intelligent') {
            this.intelligent = !this.intelligent;
        }
    }
    stepChange(v) {
        this.processAct = false;
        setTimeout(() => {
            this.processParam.ALARMDESCRIPTION = v;
            this.processAct = true;
        });
    }

    bpFilter(e, type) {
        if (type === 'sblx') {
            this.bpbjList_filter = this.bpbjList.filter(row => {
                if (row.code) {
                    return row.code.includes(e);
                }
                return false;
            });
        } else if (type === 'bpmc') {
            this.bpbjList_filter = this.bpbjList.filter(row => {
                if (row.code) {
                    return row.name.includes(e);
                }
                return false;
            });
        }
    }

}
